<template>
  <!-- 评学管理 -->
  <div>
    <InnerBreadcrumb v-model="indexKey" :path="breadPath" :showBack="true"/>
    <div class="edu-page-warp"  v-if="indexKey === '1'">
      <condition-card @reset="reset" @search="searchList" :label-width="labelWidth" style="margin-bottom: 20px;">
        <el-row :gutter="20">
          <!-- 学年学期 -->
          <el-col :span="8">
            <el-form-item :label="$t('label.schoolTerm')">
              <CalendarSelect v-model="queryParams.calendarId"></CalendarSelect>
            </el-form-item>
          </el-col>
          <!-- 状态 -->
          <el-col :span="8">
            <el-form-item :label="$t('状态')">
              <el-select v-model="queryParams.releaseState" style="width: 100%;">
                <el-option
                  v-for="item in statusList"
                  :key="item.code"
                  :label="item.statusName"
                  :value="item.code">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </condition-card>

      <!-- 表格card -->
      <el-card shadow="never">
        <div class="edu-page-title">{{title}}</div>
        <div class="edu-opertion-bar">
          <div class="float-left">
          <KeywordInput
              v-model="queryParams.managementName"
              :placeholder="$t('请输入主题名')"
              @enter="searchList"/>
          </div>
          <div class="float-right">
            <el-button type="primary" @click="exportData()">{{$t('message.export')}}</el-button>
            <el-button type="primary" v-if="!ifFacultyUser" @click="addClick()">{{$t('message.add')}}</el-button>
          </div>
        </div>
        <!-- 主页表格 -->
        <edu-table :url="url" ref="mainTable" :order="true" :selection="true">
          <edu-table-column :label="$t('label.schoolTerm')" min-width="120px" prop="calendarName"></edu-table-column>
          <edu-table-column :label="$t('问卷主题名')" min-width="120px">
            <template slot-scope="scope">
              <el-button type="text" @click="themeClick(scope.row)">{{scope.row.managementName}}</el-button>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('评学开始时间')" prop="startTime" min-width="120px"></edu-table-column>
          <edu-table-column :label="$t('评学结束时间')" prop="endTime" min-width="120px"></edu-table-column>
          <edu-table-column :label="$t('是否强制')">
            <template slot-scope="scope">
              <el-switch :disabled="ifFacultyUser" @change="changeForceState(scope.row)" :value="scope.row.forceState" active-value="1" inactive-value="0"></el-switch>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('状态')">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.releaseState === '0'" type="danger">
                {{ `未发布` }}
              </el-tag>
              <el-tag v-if="scope.row.releaseState === '1'" type="info">
                {{ `已完成` }}
              </el-tag>
              <el-tag v-if="scope.row.releaseState === '2'" type="success">
                {{ `已发布` }}
              </el-tag>
              <el-tag v-if="scope.row.releaseState === '3'" type="warning">
                {{ `已撤销` }}
              </el-tag>
            </template>
          </edu-table-column>
          <edu-table-column :label="$t('message.operating')" min-width="160px">
            <template slot-scope="scope">
              <el-button type="text" v-if="(scope.row.releaseState === '0' || scope.row.releaseState === '3') && !ifFacultyUser" @click.stop="editClick(scope.row)">{{$t('编辑')}}</el-button>
              <el-button type="text" v-if="(scope.row.releaseState === '0' || scope.row.releaseState === '3') && !ifFacultyUser" @click.stop="releaseClick(scope.row)">{{$t('发布')}}</el-button>
              <el-button type="text" v-if="(scope.row.releaseState === '0' || scope.row.releaseState === '3') && !ifFacultyUser" @click.stop="deleteClick(scope.row)">{{$t('删除')}}</el-button>
              <el-button type="text" @click.stop="previewClick(scope.row)">{{$t('预览')}}</el-button>
              <el-button type="text" v-if="scope.row.releaseState === '2' && !ifFacultyUser" @click.stop="withdrawClick(scope.row)">{{$t('撤销')}}</el-button>
            </template>
          </edu-table-column>
        </edu-table>
        <edu-export-dialog :disabled="exportButton" :title="$t('message.prompt')" ref="downloadRef" :data="exportResult"></edu-export-dialog>
      </el-card>
    </div>
    <!-- 问卷主题 -->
    <div v-if="indexKey === '2'">
      <QuestionnaireTheme
        :ifRelease="ifRelease"
        @goToCheck="goToCheck"
        :pageFrom="'evaLearn'"
        :ifShowNotFillPeople="false"
        :ifShowTeacherParam="false"
        :teacherComeIn="true"

        >
      </QuestionnaireTheme>
    </div>
    <!-- 新增/编辑 -->
    <div v-if="indexKey === '3'">
      <AddQuestionaireOfLearn
        @goToAddNext="goToAddNext"
        @onlyGoBack="onlyGoBack"
        :ifEdit="ifEdit"
        :ifPrev="ifPrev"
        @goToPreview="goToPreview">
      </AddQuestionaireOfLearn>
    </div>
    <!-- 问卷预览 -->
    <div v-if="indexKey === '4'">
      <QuestionsPreview
        :data="questionList"
        :typeTitle="'预览'"
        :title="childTitle"
        :foreword="foreword"
        :pageType="'preview'"
        :maintainShow="false"
        :exportShow="false">
      </QuestionsPreview>
    </div>
    <div v-if="indexKey === '5'">
      <ObjectSetLearnEvaluation
        :ifEdit="ifEdit"
        @onlyGoBack="onlyGoBack"
        @editGoBack="editGoBack"
        @goToAddOrEdit="goToAddOrEdit">
      </ObjectSetLearnEvaluation>
    </div>
    <div v-if="indexKey === '6'">
      <CheckResult :checkData="checkData" :ifProcess="ifProcess" :pageFrom='pageFrom'></CheckResult>
    </div>
    <edu-dialog
      :title="'预览'"
      ref="templateDialog"
      :width="'80%'"
      :showFooter="false"
      :showButtons="true"
      :showConfirmBtn="false"
      @close="templateDialogClose">
      <QuestionsPreview
        :data="questionList"
        :pageType="'preview'"
        :title="childTitle"
        :foreword="foreword"
        :maintainShow="false"
        :exportShow="false">
      </QuestionsPreview>
    </edu-dialog>
  </div>

</template>
<script>
import baseUrl from 'common/src/api/teachingEvaluation/env'
import SchoolCalendarApi from "common/src/api/calendars";
import QuestionnaireTheme from './component/QuestionnaireTheme'
import courseEvaluationApi from 'common/src/api/teachingEvaluation/courseEvaluation'
import AddQuestionaireOfLearn from './component/AddQuestionaireOfLearn'
import ObjectSetLearnEvaluation from './component/ObjectSetLearnEvaluation'
import QuestionsPreview from './component/QuestionnairePreview/QuestionsPreview'
import templateApi from 'common/src/api/teachingEvaluation/template'
import CheckResult from './component/CheckResult'
export default {
  components: {
    QuestionnaireTheme,
    AddQuestionaireOfLearn,
    ObjectSetLearnEvaluation,
    QuestionsPreview,
    CheckResult
  },
  data() {
    return {
      url: `${baseUrl}/teacherManagement/getPageList`,
      title: '评学问卷列表',
      labelWidth: '120px',
      exportButton: false,
      exportResult: null,
      currentCalendarId: '',
      ifEdit: false,
      ifProcess: false,
      indexKey: '1',
      queryParams: {
        calendarId: '',
        releaseState: '',
        managementName: ''
      },
      statusList: [
        {
          statusName: '未发布',
          code: 0
        },
        {
          statusName: '已完成',
          code: 1
        },
        {
          statusName: '已发布',
          code: 2
        },
        {
          statusName: '已撤销',
          code: 3
        }
      ],
      rules: {
        managementName: [
          { required: true, message: '请填写问卷主题名', trigger: 'blur' }
        ],
        templateMainId: [
          { required: true, message: '请选择评学评价模板', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择评学权限开始时间', trigger: 'change' }
        ],
        endTime: [
          { required: true, message: '请选择评学权限结束时间', trigger: 'change' }
        ],
        introduction: [
          { required: true, message: '请填写评学问卷前言', trigger: 'blur' }
        ]
      },
      questionList: [],
      childTitle: '',
      foreword: '',
      checkData: {},
      breadPath: {
        label: this.$t('评学管理'),
        key: "1",
        children: [
          {
            key: "2",
            label: this.$t('问卷主题'),
            children: [
              {
                key: "6",
                label: this.$t('查看')
              }
            ]
          },
          {
            key: "3",
            label: this.$t('新增'),
            children: [
              {
                key: "5",
                label: this.$t('评学对象配置')
              }
            ]
          },
          {
            key: "4",
            label: this.$t('预览')
          }
        ]
      },
      ifPrev: false, // 是否上一步进入新增页面
      ifRelease: true,
      ifFacultyUser: false
    }
  },
  computed: {
  },
  created() {
    courseEvaluationApi.judgeLoginRole().then(res => {
      if (res.data) {
        this.ifFacultyUser = true
        for (let key in res.data) {
          sessionStorage.setItem('currFacultyCode', key)
        }
      } else {
        this.ifFacultyUser = false
        sessionStorage.setItem('currFacultyCode', '')
      }
    })
    this.$router.push({
      query: {}
    });
  },
  mounted() {
    // this.searchList()
    this.getCurrentTermCalendar().then(resp => {
      this.currentCalendarId = resp.data.schoolCalendar.id;
    });
    this.$nextTick(() => {
      this.searchList()
    })
  },
  methods: {
    // 获取当前学年学期
    async getCurrentTermCalendar(){
      return await SchoolCalendarApi.currentTermCalendar();
    },
   // 查询
    searchList() {
      this.$refs.mainTable.pageNum = 1;
      this.$refs.mainTable.search(this.queryParams);
    },
    // 重置查询参数
    reset() {
      for (const key in this.queryParams) {
        this.queryParams[key] = "";
      }
      this.queryParams.calendarId = this.currentCalendarId;
      this.searchList()
    },
    themeClick(row) {
      if (row.releaseState == '0') {
        this.$confirm("问卷未发布，是否确认查看?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.ifRelease = false
          this.$router.push({
            query: {
              managementId: row.managementId,
              calendarId: this.queryParams.calendarId
            }
          })
          this.indexKey = '2';
        })
      } else {
        this.ifRelease = true
        this.$router.push({
          query: {
            managementId: row.managementId,
            calendarId: this.queryParams.calendarId
          }
        })
        this.indexKey = '2';
      }
    },
    // 删除点击
    deleteClick(row) {
      let param = {
        managementId: row.managementId
      }
      let tip = '是否确认删除？'
      courseEvaluationApi.judgeIfTeacherEvaWrite(param).then(res => {
        if (res.data) {
          tip = '已有人填写该问卷，是否确认删除？'
        } else {
          tip = '是否确认删除？'
        }
        this.$confirm(this.$t(tip), this.$t("message.prompt"), {
          confirmButtonText: this.$t("message.confirm"),
          cancelButtonText: this.$t("message.cancel"),
          type: "warning"
        }).then(() => {
          courseEvaluationApi.deleteTeacherEva(param).then(res => {
            if (res.code === 200) {
              this.$message.success('删除成功');
              this.searchList();
            }
          })
        });
      })
    },
    // 新增点击
    addClick() {
      this.breadPath.children[1].label = this.$t('新增')
      this.ifEdit = false
      this.ifPrev = false
      this.indexKey = '3';
    },
    // 编辑点击
    editClick(row) {
      this.breadPath.children[1].label = this.$t('编辑')
      this.ifEdit = true
      this.ifPrev = false
      this.indexKey = '3';
      this.$router.push({
        query: {
          managementId: row.managementId,
          calendarId: this.queryParams.calendarId,
          ifWithdraw: row.releaseState === '3' ? true : false
        }
      })
    },
    // 主题页面点击查看
    goToCheck(value,pageFrom) {
      if(pageFrom) {
        this.pageFrom = pageFrom
        this.breadPath.children[0].children[0].label = '统计'
      } else {
        this.pageFrom = ''
        this.breadPath.children[0].children[0].label = '查看'
      }
      this.checkData = value
      this.indexKey = '6'
    },
    // 下一步
    nextStep() {
      this.indexKey = '3';
    },
    // 新增时子组件点击下一步 进入对象设置页面
    goToAddNext() {
      this.indexKey = '5';
    },
    // 新增取消时 返回当前页面
    onlyGoBack() {
      this.indexKey = '1';
    },
    // 编辑页面返回上一级
    editGoBack() {
      this.ifEdit = true
      this.ifPrev = false
      this.indexKey = '3';
    },
    // 对象配置返回上一级
    goToAddOrEdit() {
      this.ifEdit = false
      this.ifPrev = true
      this.indexKey = '3';
    },
    // 发布click
    releaseClick(row) {
      const judgeParam = {
        id: row.templateMainId
      }
      templateApi.judgeWeight(judgeParam).then(res => {
        if (res.data == 0) {
          this.$message.error('当前问卷所用模板权重之和不等于100')
          return
        } else {
          this.$confirm(this.$t('确定要发布问卷吗？'), this.$t("message.prompt"), {
            confirmButtonText: this.$t("message.confirm"),
            cancelButtonText: this.$t("message.cancel"),
            type: "warning"
          }).then(() => {
            let param = {
              managementId: row.managementId,
              templateMainId: row.templateMainId
            }
            courseEvaluationApi.releaseTeacherEva(param).then(res => {
              if (res.code === 200) {
                this.$message.success('发布成功');
                this.searchList();
              }
            })
          });
        }
      })
    },
    // 强制
    changeForceState(row) {
      if (row.forceState === '1') {
        let param = {
          forceState: '0',
          managementId: row.managementId
        }
        courseEvaluationApi.forceTeacherEva(param).then(res => {
          if (res.code === 200) {
            this.$message.success('已取消强制');
            this.$refs.mainTable.search(this.queryParams);
          }
        })
      } else if (row.forceState === '0') {
        let param = {
          forceState: '1',
          managementId: row.managementId
        }
        courseEvaluationApi.forceTeacherEva(param).then(res => {
          if (res.code === 200) {
            this.$message.success('已强制');
            this.$refs.mainTable.search(this.queryParams);
          }
        })
      }
      // this.$confirm(this.$t('确定要强制执行该问卷吗？'), this.$t("message.prompt"), {
      //   confirmButtonText: this.$t("message.confirm"),
      //   cancelButtonText: this.$t("message.cancel"),
      //   type: "warning"
      // }).then(() => {
      // })
    },
    // 关闭弹窗
    templateDialogClose() {
      this.$refs.templateDialog.close()
    },
    // 新增时预览模板
    goToPreview(value) {
      this.$router.push({
        query: {
          id: value.templateMainId,
          name: value.templateMainName,
          managementId: value.managementId,
          calendarId: value.calendarId
        }
      })
      let param = {
        id: value.templateMainId
      }
      this.childTitle = value.managementName
      this.foreword = value.introduction
      templateApi.getQuestionDetail(param).then(res => {
        if (res.code === 200) {
          this.questionList = res.data
          this.questionList.forEach(item => {
            // titleType: {1.单选 2.多选 3.问答}
            if (item['options']) {
              item['options'] = JSON.parse(item['options'])
            }
          })
          this.$refs.templateDialog.open()
        }
      })
    },
    // 预览click
    previewClick(row) {
      // console.log('row', row.introduction)
      this.$router.push({
        query: {
          id: row.templateMainId,
          name: row.templateMainName
        }
      })
      let param = {
        id: row.templateMainId
      }
      this.childTitle = row.managementName
      this.foreword = row.introduction
      templateApi.getQuestionDetail(param).then(res => {
        if (res.code === 200) {
          this.questionList = res.data
          this.questionList.forEach(item => {
            // titleType: {1.单选 2.多选 3.问答}
            if (item['options']) {
              item['options'] = JSON.parse(item['options'])
            }
          })
        }
      })
      this.indexKey = '4'
    },
    // 撤销
    withdrawClick(row) {
      let param = {
        managementId: row.managementId
      }
      this.$confirm(this.$t('result.sureWithdrawData'), this.$t("message.prompt"), {
        confirmButtonText: this.$t("message.confirm"),
        cancelButtonText: this.$t("message.cancel"),
        type: 'warning'
      }).then(_ => {
        courseEvaluationApi.withdrawTeacherEva(param).then(res => {
          if (res.code === 200) {
            this.$message.success('撤销成功');
            this.searchList();
          }
        })
      });
    },
    // 导出
    exportData() {
      if (this.$refs.mainTable.getData().length <= 0) {
        this.$message.error(this.$t('result.noExportData'));
        return;
      }
      const checkDatas = this.$refs.mainTable.getCheckData();
      let ids = checkDatas.map(item => {
        return item.managementId
      })
      let param = JSON.parse(JSON.stringify(this.queryParams))
      param.managementIdList = ids
      this.exportResult = null;
      this.$refs.downloadRef.open();
      this.exportButton = true;
      courseEvaluationApi.exportTeacherEvaList(param).then(res =>{
        if (res.code == 200) {
          this.delayRequest(res.data.key);
        } else {
          this.$refs.downloadRef.close();
          this.exportButton = false;
        }
      })
    },
    // 导出异步
    delayRequest(key) {
      setTimeout(() => {
        courseEvaluationApi.exportStatus(key).then(res => {
          this.exportResult = res.data;
          if (res.code == 200 && res.data.status) {
            this.exportButton = false;
            let path =
              `${baseUrl}/file/exportExcel?path=` +
              res.data.path;
            // window.open(path);
            window.location.href = path;
            this.$message.success(this.$t('result.exportSuccessfully'));
            this.$refs.downloadRef.close();
          } else {
            this.delayRequest(key);
          }
        });
      }, 3000);
    }
  },
  watch: {
    indexKey(value) {
      if (value == '1') {
        this.$router.push({
          query: {}
        })
        this.$nextTick(() => {
          this.searchList();
        })
      }
    }
  }
}
</script>
<style lang="scss">
</style>
